<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Hash;
use App\Models\Linkslists;
use App\Models\Linkslistsminapps;
use App\Models\Users;
use App\Models\Memberorders;
use App\Models\Usersinvitations;
use App\Models\Linkscard;
use App\Models\Linkslistssetting;
use App\Charts\SampleChart;
use Auth,Exception,Log,DB;

class ManageController extends Controller
{
    public function linkList(Request $request)
    {
        $users = Auth::user();
        if($users->authority != 3) return redirect("/admin/links_lists/lists")->with("status","error")->with("msg","您无权执行本操作!");
        $links = Linkslists::manageLinkLists($request->users_id,$request->title,$request->links_id);
        $linkAppids = $links->pluck("appid")->unique()->all();
        $minapps = Linkslistsminapps::getLinkListMinappAll($linkAppids);
        foreach ($links as $link) {
            $minapp = $minapps->where("appid",$link->appid)->first();
            $link->mini_name = empty($minapp) ? "-" : $minapp->name;
        }
        $platfromTypes = ["","公众号文章","公众号客服","个人客服","小程序","小程序","小程序-点击版","复制搜索","个人微信二维码","微信群二维码","朋友圈","小程序码","公众号二维码模式","H5链接模式","视频号主页","视频号直播","视频号视频"];
        return view("admin.manage.link_list",["links"=>$links,"platfromTypes"=>$platfromTypes,"condition"=>$request->all()]);
    }

    public function userList(Request $request)
    {
        $nike = str_replace(" ","",$request->nike);
        if(preg_match("/^1[23456789]{1}\d{9}$/",$nike)) {
            $keyword = "username";
        } else {
            if (is_numeric($nike)) {
                $keyword = "id";
            } else {
                $keyword = "nike";
            }
        }
        $users = Auth::user();
        if ($users->authority != 3) return redirect("/admin/links_lists/lists")->with("status","error")->with("msg","您无权访问本链接！");
        $users = Users::linksUsersList($keyword,$nike);
        $users_ids = $users->pluck("id")->all();
        $memberorders = Memberorders::getUsersLastOrders($users_ids);
        $usersinvitations = Usersinvitations::adminGetUsersInvitations($users_ids);
        $linkslists = Linkslists::getUsersLinksListsCount($users_ids);
        $products = Memberorders::$products;
        foreach ($users as $user) {
            $memberorder = $memberorders->where("users_id",$user->id)->first();
            $linkslist = $linkslists->where("users_id",$user->id)->first();
            if (!empty($linkslist)) {
                $user->links_count = $linkslist->links_count;
            } else {
                $user->links_count = 0;
            }
            if (!empty($memberorder)) {
                $product = collect($products)->where("id",$memberorder->product_id)->first();
                $user->product_id = empty($product) ? "其他" : $product["title"];
                if ($memberorder->end_time < time()) {
                    $user->member_time = "已过期";
                } else {
                    $user->member_time = date("Y-m-d",$memberorder->end_time);
                }
            } else {
                $user->member_time = "-";
                $user->product_id = "-";
            }

            $usersinvitation = $usersinvitations->where("users_id",$user->id)->first();
            if (!empty($usersinvitation)) {
                $user->invitate_name = empty($usersinvitation->nike) ? $usersinvitation->username : $usersinvitation->nike;
                $user->users_invitation_id = $usersinvitation->users_invitation_id;
            } else {
                $user->invitate_name = "";
                $user->users_invitation_id = "";
            }
        }
        $devices = ["","电脑","手机网页","小程序","微信网页"];
        $condition = $request->all();
        return view('admin.manage.user_list',["users"=>$users,"condition"=>$condition,"devices"=>$devices]);
    }

    public function miniappList(Request $request)
    {
        $users = Auth::user();
        if($users->authority != 3) return redirect("/admin/links_lists/lists")->with("status","error")->with("msg","您无权执行本操作!");
        $linkListMinapps = Linkslistsminapps::adminLinkListMinapp($request->users_id,$request->name,$request->appid);
        return view("admin.manage.miniapp_list",["linkListMinapps"=>$linkListMinapps,"condition"=>$request->all()]);
    }

    public function userLogin(Request $request,$id)
    {
        $users = Auth::user();
        if($users->authority != 3) return redirect("/admin/links_lists/lists")->with("status","error")->with("msg","您无权执行本操作!");
        Auth::loginUsingId($id);
        return redirect("/admin/links_lists/lists")->with("status","success")->with("msg","登录权限切换成功!");
    }

    public function rechargeStatic(Request $request)
    {
        $user = Auth::user();
        if ($user->authority != 3) return redirect("/admin/links_lists/lists")->with("status","error")->with("msg","您无权操作本功能！");
        if (empty($request->date)) {
            $start_time = strtotime(date("Y-m-01",time()));
            $end_time = strtotime("+1 month");
        } else {
            $start_time = strtotime($request->date."-01");
            $end_time = strtotime("+1 month",strtotime($request->date."-01"));
        }
        $rechargesLists = DB::select('SELECT DATE_FORMAT(FROM_UNIXTIME(created_at),"%m-%d") as `day`,SUM(price) as money FROM member_orders WHERE created_at >= ? AND created_at <= ? AND pay_status = 3 GROUP BY day', [$start_time,$end_time]);

        $labels = [];
        $moneys = [];

        foreach ($rechargesLists as $rechargesList) {
            $labels[] = $rechargesList->day;
            $moneys[] = $rechargesList->money;
        }
        $totalmoneys = collect($moneys)->sum();

        $chart = new SampleChart;
        $chart->labels($labels);
        $chart->dataset('会员收入', 'line', $moneys)->color("rgb(15, 127, 254)")->backgroundcolor("rgb(97, 161, 254,0.2)");

        return view('admin.manage.recharge_static',["chart"=>compact('chart'),"totalmoneys"=>$totalmoneys]);
    }

    public function usersStatics(Request $request)
    {
        $user = Auth::user();
        if ($user->authority != 3) return back()->with("status","error")->with("msg","您无权操作本功能！");
        if (empty($request->date)) {
            $start_time = strtotime(date("Y-m-01",time()));
            $end_time = strtotime("+1 month");
        } else {
            $start_time = strtotime($request->date."-01");
            $end_time = strtotime("+1 month",strtotime($request->date."-01"));
        }
        $usersLists = DB::select('SELECT DATE_FORMAT(FROM_UNIXTIME(created_at),"%m-%d") as `day`,count(id) as number FROM users WHERE created_at >= ? AND created_at <= ? GROUP BY day', [$start_time,$end_time]);

        $labels = [];
        $numbers = [];

        foreach ($usersLists as $usersList) {
            $labels[] = $usersList->day;
            $numbers[] = $usersList->number;
        }

        $totalusers = collect($numbers)->sum();

        $chart = new SampleChart;
        $chart->labels($labels);
        $chart->dataset('注册用户数', 'line', $numbers)->color("rgb(15, 127, 254)")->backgroundcolor("rgb(97, 161, 254,0.2)");

        return view('admin.manage.users_static',["chart"=>compact('chart'),"totalusers"=>$totalusers]);
    }

    public function memberList(Request $request)
    {
        $users = Auth::user();
        if($users->authority != 3) return redirect("/admin/links_lists/lists")->with("status","error")->with("msg","您无权执行本操作!");
        $pay_status = empty($request->pay_status) ? 3 :$request->pay_status;
        $memberorders = Memberorders::memberOrdersLists($pay_status,$request->product_id);
        $condition = $request->all();
        return view('admin.manage.member_list',["memberorders"=>$memberorders,"condition"=>$condition]);
    }

    public function linksCard(Request $request)
    {
        $users = Auth::user();
        if($users->authority != 3) return redirect("/admin/links_lists/lists")->with("status","error")->with("msg","您无权执行本操作!");
        $linkCards = Linkscard::adminLinksCard($request->title,$request->describe,$request->links_id);
        return view('admin.manage.links_card',["linkCards"=>$linkCards]);
    }

    public function linksCardDisable(Request $request,$links_id)
    {
        $users = Auth::user();
        if($users->authority != 3) return redirect("/admin/links_lists/lists")->with("status","error")->with("msg","您无权执行本操作!");
        $linkCard = Linkscard::linkCardDetial($links_id);
        $disable = $linkCard->disable == 1 ? 2 : 1;
        Linkscard::linkCardDisableUpdate($links_id,$disable);
        return redirect("/admin/manage/links_card")->with("status","success")->with("msg","卡片禁用状态修改成功!");
    }

    public function linkSearch(Request $request)
    {
        $users = Auth::user();
        if($users->authority != 3) return redirect("/admin/links_lists/lists")->with("status","error")->with("msg","您无权执行本操作!");
        $links = Linkslistssetting::linkSearch($request->miniapp_style,$request->keyword);
        return view("admin.manage.link_search",["links"=>$links,"condition"=>$request->all()]);
    }
}
